<script lang="ts" setup>
import type { AiChatApi } from '#/api/core/ai-chat';

import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue';
import { message } from 'ant-design-vue';
import { Ellipsis } from 'lucide-vue-next';
import { $t } from '#/locales';
import { 
  createSessionApi, 
  getSessionsApi, 
  sendMessageApi, 
  getMessagesApi,
  deleteSessionApi,
  updateSessionApi,
  getModelsApi
} from '#/api/core/ai-chat';

// 组件选项
defineOptions({
  name: 'AiChat',
  inheritAttrs: false,
});

// 响应式状态
const loading = ref(false);
const sending = ref(false);
const sessions = ref<AiChatApi.ChatSession[]>([]);
const currentSession = ref<AiChatApi.ChatSession | null>(null);
const messages = ref<AiChatApi.ChatMessage[]>([]);
const models = ref<AiChatApi.AiModel[]>([]);
const messageInput = ref('');
const messagesContainer = ref<HTMLElement>();

// 表单状态
const sessionForm = reactive({
  title: '',
  model: '',
  visible: false,
});

// 计算属性
const currentModel = computed(() => {
  return models.value.find(m => m.id === currentSession.value?.settings?.model) || models.value[0];
});

const hasMessages = computed(() => messages.value.length > 0);

// 方法定义
async function loadSessions() {
  try {
    loading.value = true;
    const result = await getSessionsApi({ pageSize: 100 });
    sessions.value = result.sessions;
    
    // 如果没有当前会话且有会话列表，选择第一个
    if (!currentSession.value && sessions.value.length > 0) {
      await selectSession(sessions.value[0]);
    }
  } catch (error) {
    console.error('加载会话列表失败:', error);
    message.error($t('page.aiChat.loadFailed'));
  } finally {
    loading.value = false;
  }
}

async function loadModels() {
  try {
    const result = await getModelsApi();
    models.value = result.models;
  } catch (error) {
    console.error('加载模型列表失败:', error);
    message.error($t('page.aiChat.loadFailed'));
  }
}

async function selectSession(session: AiChatApi.ChatSession) {
  currentSession.value = session;
  await loadMessages(session.id);
}

async function loadMessages(sessionId: string) {
  try {
    loading.value = true;
    const result = await getMessagesApi({ sessionId, pageSize: 100 });
    messages.value = result.messages.sort((a, b) => a.timestamp - b.timestamp);
    
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  } catch (error) {
    console.error('加载消息失败:', error);
    message.error($t('page.aiChat.loadFailed'));
  } finally {
    loading.value = false;
  }
}

// 创建新会话
const createNewSession = () => {
  const newSession: ChatSession = {
    id: Date.now().toString(),
    title: $t('page.aiChat.newChat'),
    messages: [],
    model: 'gpt-3.5-turbo',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };
  
  sessions.value.push(newSession);
  currentSessionId.value = newSession.id;
  message.success($t('page.aiChat.createSuccess'));
};

async function deleteSession(session: AiChatApi.ChatSession) {
  try {
    await deleteSessionApi(session.id);
    sessions.value = sessions.value.filter(s => s.id !== session.id);
    
    if (currentSession.value?.id === session.id) {
      currentSession.value = null;
      messages.value = [];
      
      // 选择下一个会话
      if (sessions.value.length > 0) {
        await selectSession(sessions.value[0]);
      }
    }
    
    message.success($t('page.aiChat.deleteSuccess'));
  } catch (error) {
    console.error('删除会话失败:', error);
    message.error($t('page.aiChat.loadFailed'));
  }
}

async function sendMessage() {
  if (!messageInput.value.trim() || !currentSession.value || sending.value) {
    return;
  }

  const content = messageInput.value.trim();
  messageInput.value = '';

  try {
    sending.value = true;
    
    // 添加用户消息到界面
    const userMessage: AiChatApi.ChatMessage = {
      id: Date.now().toString(),
      role: 'user',
      content,
      type: 'text',
      timestamp: Date.now(),
      sessionId: currentSession.value.id,
    };
    messages.value.push(userMessage);
    
    await nextTick();
    scrollToBottom();

    // 发送消息到服务器
    const result = await sendMessageApi({
      sessionId: currentSession.value.id,
      content,
      type: 'text',
    });

    // 添加AI回复到界面
    messages.value.push(result.message);
    
    await nextTick();
    scrollToBottom();
    
  } catch (error) {
    console.error('发送消息失败:', error);
    message.error($t('page.aiChat.sendFailed'));
  } finally {
    sending.value = false;
  }
}

function scrollToBottom() {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
}

function handleKeyPress(event: KeyboardEvent) {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    sendMessage();
  }
}

function formatTime(timestamp: number) {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
  });
}

function showCreateSessionModal() {
  sessionForm.visible = true;
  sessionForm.model = models.value[0]?.id || '';
}

// 生命周期钩子
onMounted(async () => {
  await Promise.all([loadModels(), loadSessions()]);
});
</script>

<template>
  <div class="ai-chat">
    <div class="ai-chat__container">
      <!-- 左侧会话列表 -->
      <div class="ai-chat__sidebar">
        <div class="ai-chat__sidebar-header">
          <h3 class="ai-chat__sidebar-title">AI 聊天室</h3>
          <a-button type="primary" size="small" @click="showCreateSessionModal">
            新建对话
          </a-button>
        </div>
        
        <div class="ai-chat__session-list">
          <div
            v-for="session in sessions"
            :key="session.id"
            class="ai-chat__session-item"
            :class="{ 'ai-chat__session-item--active': currentSession?.id === session.id }"
            @click="selectSession(session)"
          >
            <div class="ai-chat__session-title">{{ session.title }}</div>
            <div class="ai-chat__session-meta">
              <span class="ai-chat__session-time">
                {{ formatTime(session.updatedAt) }}
              </span>
              <a-dropdown trigger="click">
                <a-button type="text" size="small" @click.stop>
                  <template #icon>
                    <ellipsis />
                  </template>
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="deleteSession(session)">
                      删除会话
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="ai-chat__main">
        <div v-if="!currentSession" class="ai-chat__empty">
          <div class="ai-chat__empty-content">
            <h3>欢迎使用 AI 聊天室</h3>
            <p>选择一个对话开始聊天，或创建新的对话</p>
            <a-button type="primary" @click="showCreateSessionModal">
              创建新对话
            </a-button>
          </div>
        </div>

        <div v-else class="ai-chat__chat">
          <!-- 聊天头部 -->
          <div class="ai-chat__header">
            <div class="ai-chat__header-info">
              <h3 class="ai-chat__header-title">{{ currentSession.title }}</h3>
              <span class="ai-chat__header-model">
                {{ currentModel?.name || '未知模型' }}
              </span>
            </div>
          </div>

          <!-- 消息列表 -->
          <div ref="messagesContainer" class="ai-chat__messages">
            <div v-if="!hasMessages" class="ai-chat__messages-empty">
              <p>开始你的第一次对话吧！</p>
            </div>
            
            <div
              v-for="message in messages"
              :key="message.id"
              class="ai-chat__message"
              :class="`ai-chat__message--${message.role}`"
            >
              <div class="ai-chat__message-avatar">
                <a-avatar v-if="message.role === 'user'" size="small">
                  用户
                </a-avatar>
                <a-avatar v-else size="small" style="background-color: #1890ff">
                  AI
                </a-avatar>
              </div>
              <div class="ai-chat__message-content">
                <div class="ai-chat__message-text">{{ message.content }}</div>
                <div class="ai-chat__message-time">
                  {{ formatTime(message.timestamp) }}
                </div>
              </div>
            </div>

            <div v-if="sending" class="ai-chat__message ai-chat__message--assistant">
              <div class="ai-chat__message-avatar">
                <a-avatar size="small" style="background-color: #1890ff">
                  AI
                </a-avatar>
              </div>
              <div class="ai-chat__message-content">
                <div class="ai-chat__message-text">
                  <a-spin size="small" /> 正在思考中...
                </div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="ai-chat__input">
            <div class="ai-chat__input-container">
              <a-textarea
                v-model:value="messageInput"
                placeholder="输入消息... (Enter 发送，Shift+Enter 换行)"
                :auto-size="{ minRows: 1, maxRows: 4 }"
                :disabled="sending"
                @keypress="handleKeyPress"
              />
              <a-button
                type="primary"
                :loading="sending"
                :disabled="!messageInput.trim()"
                @click="sendMessage"
              >
                发送
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建会话弹窗 -->
    <a-modal
      v-model:open="sessionForm.visible"
      title="创建新对话"
      @ok="createSession"
    >
      <a-form layout="vertical">
        <a-form-item label="对话标题">
          <a-input
            v-model:value="sessionForm.title"
            placeholder="请输入对话标题"
          />
        </a-form-item>
        <a-form-item label="AI 模型">
          <a-select
            v-model:value="sessionForm.model"
            placeholder="请选择 AI 模型"
          >
            <a-select-option
              v-for="model in models"
              :key="model.id"
              :value="model.id"
            >
              {{ model.name }} - {{ model.description }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.ai-chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.ai-chat__container {
  flex: 1;
  display: flex;
  height: 100%;
}

.ai-chat__sidebar {
  width: 300px;
  border-right: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  background-color: #fafafa;
}

.ai-chat__sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ai-chat__sidebar-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.ai-chat__session-list {
  flex: 1;
  overflow-y: auto;
}

.ai-chat__session-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ai-chat__session-item:hover {
  background-color: #f5f5f5;
}

.ai-chat__session-item--active {
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.ai-chat__session-title {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.ai-chat__session-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ai-chat__session-time {
  font-size: 12px;
  color: #999;
}

.ai-chat__main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.ai-chat__empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.ai-chat__empty-content {
  text-align: center;
}

.ai-chat__empty-content h3 {
  margin-bottom: 8px;
  color: #333;
}

.ai-chat__empty-content p {
  margin-bottom: 16px;
  color: #666;
}

.ai-chat__chat {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.ai-chat__header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
}

.ai-chat__header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.ai-chat__header-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.ai-chat__header-model {
  font-size: 12px;
  color: #666;
  background-color: #f0f0f0;
  padding: 2px 8px;
  border-radius: 12px;
}

.ai-chat__messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fafafa;
}

.ai-chat__messages-empty {
  text-align: center;
  color: #999;
  margin-top: 100px;
}

.ai-chat__message {
  display: flex;
  margin-bottom: 16px;
  gap: 12px;
}

.ai-chat__message--user {
  flex-direction: row-reverse;
}

.ai-chat__message--user .ai-chat__message-content {
  background-color: #1890ff;
  color: white;
}

.ai-chat__message-avatar {
  flex-shrink: 0;
}

.ai-chat__message-content {
  max-width: 70%;
  background-color: white;
  border-radius: 8px;
  padding: 12px 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.ai-chat__message-text {
  line-height: 1.5;
  word-wrap: break-word;
}

.ai-chat__message-time {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  margin-top: 4px;
}

.ai-chat__message--user .ai-chat__message-time {
  color: rgba(255, 255, 255, 0.7);
}

.ai-chat__input {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  background-color: #fff;
}

.ai-chat__input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.ai-chat__input-container .ant-input {
  flex: 1;
}
</style>